using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Win32;
using System.IO;
using Newtonsoft.Json;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 提示词配置对话框
    /// </summary>
    public partial class PromptConfigDialog : Window
    {
        private readonly ILogger<PromptConfigDialog> _logger;
        private readonly IPromptConfigService _promptConfigService;
        private List<PromptConfig> _configs = new();
        private PromptConfig? _currentConfig;

        public PromptConfigDialog()
        {
            InitializeComponent();
            
            _logger = App.ServiceProvider?.GetService<ILogger<PromptConfigDialog>>() 
                ?? throw new InvalidOperationException("无法获取日志服务");
            
            _promptConfigService = App.ServiceProvider?.GetService<IPromptConfigService>() 
                ?? throw new InvalidOperationException("无法获取提示词配置服务");

            Loaded += PromptConfigDialog_Loaded;
        }

        private async void PromptConfigDialog_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await LoadConfigsAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载提示词配置时发生错误");
                MessageBox.Show($"加载提示词配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载所有配置
        /// </summary>
        private async Task LoadConfigsAsync()
        {
            try
            {
                _configs = await _promptConfigService.GetAllConfigsAsync();
                
                // 如果没有配置，创建默认配置
                if (!_configs.Any())
                {
                    var newDefaultConfig = await _promptConfigService.CreateDefaultConfigAsync();
                    _configs.Add(newDefaultConfig);
                }

                ConfigListBox.ItemsSource = _configs;

                // 选择默认配置或第一个配置
                var defaultConfig = _configs.FirstOrDefault(c => c.IsDefault) ?? _configs.FirstOrDefault();
                if (defaultConfig != null)
                {
                    ConfigListBox.SelectedItem = defaultConfig;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载配置列表失败");
                throw;
            }
        }

        /// <summary>
        /// 配置选择变更事件
        /// </summary>
        private void ConfigListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ConfigListBox.SelectedItem is PromptConfig config)
            {
                LoadConfigToUI(config);
            }
        }

        /// <summary>
        /// 将配置加载到界面
        /// </summary>
        private void LoadConfigToUI(PromptConfig config)
        {
            _currentConfig = config;
            
            ConfigNameTextBox.Text = config.Name;
            ConfigDescriptionTextBox.Text = config.Description;
            IsDefaultCheckBox.IsChecked = config.IsDefault;
            
            OverallOutlinePromptTextBox.Text = config.OverallOutlinePrompt;
            WorldSettingPromptTextBox.Text = config.WorldSettingPrompt;
            VolumeOutlinePromptTextBox.Text = config.VolumeOutlinePrompt;
            ChapterOutlinePromptTextBox.Text = config.ChapterOutlinePrompt;
            ChapterContentPromptTextBox.Text = config.ChapterContentPrompt;
            TimelineUpdatePromptTextBox.Text = config.TimelineUpdatePrompt;
        }

        /// <summary>
        /// 从界面获取配置
        /// </summary>
        private PromptConfig GetConfigFromUI()
        {
            var config = _currentConfig ?? new PromptConfig();
            
            config.Name = ConfigNameTextBox.Text.Trim();
            config.Description = ConfigDescriptionTextBox.Text.Trim();
            config.IsDefault = IsDefaultCheckBox.IsChecked == true;
            config.UpdatedAt = DateTime.Now;
            
            config.OverallOutlinePrompt = OverallOutlinePromptTextBox.Text;
            config.WorldSettingPrompt = WorldSettingPromptTextBox.Text;
            config.VolumeOutlinePrompt = VolumeOutlinePromptTextBox.Text;
            config.ChapterOutlinePrompt = ChapterOutlinePromptTextBox.Text;
            config.ChapterContentPrompt = ChapterContentPromptTextBox.Text;
            config.TimelineUpdatePrompt = TimelineUpdatePromptTextBox.Text;
            
            return config;
        }

        /// <summary>
        /// 新建配置
        /// </summary>
        private void NewConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var newConfig = new PromptConfig
                {
                    Name = "新配置",
                    Description = "请输入配置描述",
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                };

                LoadConfigToUI(newConfig);
                ConfigNameTextBox.Focus();
                ConfigNameTextBox.SelectAll();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建新配置时发生错误");
                MessageBox.Show($"创建新配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var config = GetConfigFromUI();
                
                // 验证配置
                if (string.IsNullOrWhiteSpace(config.Name))
                {
                    MessageBox.Show("请输入配置名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 保存配置
                if (config.Id == 0)
                {
                    await _promptConfigService.SaveConfigAsync(config);
                }
                else
                {
                    await _promptConfigService.UpdateConfigAsync(config);
                }

                // 如果设为默认，更新默认配置
                if (config.IsDefault)
                {
                    await _promptConfigService.SetDefaultConfigAsync(config.Id);
                }

                // 重新加载配置列表
                await LoadConfigsAsync();
                
                MessageBox.Show("配置保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存配置时发生错误");
                MessageBox.Show($"保存配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 设为默认配置
        /// </summary>
        private async void SetDefault_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    await _promptConfigService.SetDefaultConfigAsync(_currentConfig.Id);
                    await LoadConfigsAsync();
                    MessageBox.Show("已设为默认配置", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置默认配置时发生错误");
                MessageBox.Show($"设置默认配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        private async void DeleteConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    var result = MessageBox.Show($"确定要删除配置 '{_currentConfig.Name}' 吗？", 
                        "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        await _promptConfigService.DeleteConfigAsync(_currentConfig.Id);
                        await LoadConfigsAsync();
                        MessageBox.Show("配置删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除配置时发生错误");
                MessageBox.Show($"删除配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出配置
        /// </summary>
        private async void ExportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    var saveDialog = new SaveFileDialog
                    {
                        Filter = "JSON文件|*.json",
                        FileName = $"{_currentConfig.Name}_提示词配置.json"
                    };

                    if (saveDialog.ShowDialog() == true)
                    {
                        await _promptConfigService.ExportConfigAsync(_currentConfig.Id, saveDialog.FileName);
                        MessageBox.Show("配置导出成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出配置时发生错误");
                MessageBox.Show($"导出配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导入配置
        /// </summary>
        private async void ImportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openDialog = new OpenFileDialog
                {
                    Filter = "JSON文件|*.json"
                };

                if (openDialog.ShowDialog() == true)
                {
                    var config = await _promptConfigService.ImportConfigAsync(openDialog.FileName);
                    if (config != null)
                    {
                        await LoadConfigsAsync();
                        ConfigListBox.SelectedItem = config;
                        MessageBox.Show("配置导入成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入配置时发生错误");
                MessageBox.Show($"导入配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
